package com.rj.bd.sys.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @desc 响应跨域请求过滤器
 * @author 白世俊
 * @datetime: 2024-12-26 11:00
 */
@WebFilter("/*")
public class CrosFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
        System.out.println("全局过滤器收到请求");
        String origin = req.getHeader("Origin");
        String uri = req.getRequestURI();
        //基础resp跨域参数
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", origin);
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,Content-Type,Accept,Cookie,Authorization");
        resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        if ("OPTIONS".equals(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        System.out.println(uri);
        chain.doFilter(req, resp);
    }

}
